<template>
    <el-container>
        <el-main>

            <div style="width: 100%;height: 100px;">
                <el-tabs v-model="activeIndex" @tab-click="handleSelect">
                        <el-tab-pane label="设备管理" name="1">
                            <el-button @click="ShowIp" class = "gbtn"> 添加分组 </el-button>
                            <div v-if = "dev.length > 0" class="coldiv">
                                <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox> -->
                                <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                                <el-table
                                    ref="multipleTable"
                                    :data="dev"
                                    tooltip-effect="dark"
                                    style="width: 100%"
                                    @selection-change="handleSelectionChange"
                                    :row-class-name="tableRowClassName">
                                    <el-table-column
                                    type="selection"
                                    width="55">
                                    </el-table-column>
                                    <el-table-column
                                    label="ip地址"
                                    prop="ip"
                                    width="140">
                                    
                                    </el-table-column>
                                    <el-table-column
                                    prop="name"
                                    label="设备名"
                                    width="120">
                                    </el-table-column>
                                    <el-table-column
                                    prop="level"
                                    label="电量"
                                    show-overflow-tooltip>
                                    </el-table-column>
                                    <el-table-column
                                    prop="memory"
                                    label="内存"
                                    show-overflow-tooltip>
                                    </el-table-column>

                                    <el-table-column
                                    label="在线状态"
                                    show-overflow-tooltip>
                                    <template slot-scope="scope" >
                                    <div v-if="scope.row.Online==  true">在线</div>
                                    <div v-if="scope.row.Online==  false">离线</div>
                                    </template>
                                    </el-table-column>

                                    <el-table-column
                                    label="是否占用"
                                    show-overflow-tooltip>
                                    <template slot-scope="scope" >
                                    <div v-if="scope.row.isbusy==  true">占用</div>
                                    <div v-if="scope.row.isbusy==  false">空闲</div>
                                    </template>
                                    </el-table-column>

                                    <el-table-column
                                    prop="groups"
                                    label="分组"
                                    show-overflow-tooltip>
                                    </el-table-column>
                                </el-table>
                                <div style="margin-top: 20px">
                                    <el-button @click="toggleSelection([dev[1], dev[2]])">切换第二、第三行的选中状态
                                    </el-button>
                                    <el-button @click="toggleSelection()">
                                        取消选择
                                    </el-button>
                                </div>

                               <!--  <el-checkbox v-for="item,index in dev" :label="item.ip" :disabled ="checkgroup(item)" >  
                                    <div style="height: 30px;">
                                    <el-tooltip class="item" effect="dark" :content="tipmsg(item)" placement="top"><p>{{item.ip}}</p>
                                    </el-tooltip>
                                    </div>
                                </el-checkbox> -->
                                </el-checkbox-group>
                                <el-dialog
                                title="提示"
                                :visible.sync="dialogVisible"
                                width="30%"
                                :before-close="handleClose">
                                <span>分组信息</span>
                                <el-input v-model="msg"></el-input>
                                <span slot="footer" class="dialog-footer">
                                <el-button @click="dialogVisible = false">取 消</el-button>
                                <el-button type="primary" @click="upGroup">确 定</el-button>
                                </span>
                                </el-dialog>
                                
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="任务列表" name="2">
                            <div>
                                <el-button @click="jobdialogshow">添加任务</el-button>
                            </div>
                            <div class="coldiv" style="text-align: center;" >
                                <el-table
                                :data="joblist"
                                style="width: 100%" max-height="600">
                                <el-table-column
                                label="任务ID"
                                prop="jobid">
                                </el-table-column>
                                <el-table-column
                                label="字体名"
                                prop="font">
                                </el-table-column>
                                <el-table-column
                                label="下载目标数"
                                prop="downnum">
                                </el-table-column>
                                <el-table-column
                                label="购买目标数"
                                prop="runnum">
                                </el-table-column>
                                <el-table-column
                                label="已下载数"
                                prop="alredynum"
                                width="90">
                                </el-table-column>
                                <el-table-column
                                label="分组"
                                prop="groups"
                                width="80">
                                </el-table-column>
                                <el-table-column
                                label="渠道"
                                prop="platform"
                                width="80">
                                </el-table-column>
                                <el-table-column
                                label="服务ip"
                                width="180"
                                >
                                <!-- prop="master" -->
                                <template slot-scope="scope" v-if="scope.row.master != ''" >
                                    <el-tooltip class="item" effect="dark" :content="scope.row.SysInfo" placement="top">
                                    <el-button>{{scope.row.master}}</el-button>
                                    </el-tooltip>
                                </template>
                                </el-table-column>
                                
                                <el-table-column
                                label="状态"
                                width="280"
                                >

                                <template slot-scope="scope" >
                                    <el-tag type="danger"  v-if="scope.row.status==  '-1'"> 
                                        任务已弃用
                                    </el-tag>
                                    <el-tag type="info"  v-if="scope.row.status==  '0'">
                                    未领取
                                    </el-tag>
                                    <el-tag v-if="scope.row.status==  '1'">
                                    正在执行
                                    </el-tag>
                                    <el-tag v-if="scope.row.status==  '2'">
                                    正在执行，重新执行
                                    </el-tag>

                                    <el-tag type = 'success' v-if="scope.row.status==  '3'">
                                    已完成
                                    </el-tag>
                                    <el-tag  type = 'warning' v-if="scope.row.status==  '4'">
                                    任务被终止
                                    </el-tag>
                                    <el-tag  type = 'warning' v-if="scope.row.status==  '5'">
                                    停止，设备离线
                                    </el-tag>
                                </template>

                                </el-table-column>

                                <el-table-column
                                label="任务类型">
                                    <template slot-scope="scope" >

                                        <div v-if="scope.row.types == '1'">
                                            每日任务
                                        </div>

                                        <div v-if="scope.row.types == '2'">
                                            <!-- 周期任务 {{scope.row.}} -->
                                            周期任务
                                        </div>

                                        <div v-if="scope.row.types == '3'">
                                            一次性任务
                                        </div>

                                    </template>
                                </el-table-column>

                                <el-table-column
                                align="right">
                                <template slot="header" slot-scope="scope">
                                <!-- <el-input
                                v-model="search"
                                size="mini"
                                placeholder="输入关键字搜索"/> -->
                                <el-autocomplete
                                v-model="search"
                                :fetch-suggestions="querySearchAsync"
                                placeholder="输入字体名搜索"
                                @select="handleSelect">
                                </el-autocomplete>

                                </template>
                                
                                </el-table-column>
                                <el-table-column
                                fixed="right"
                                label="操作"
                                width="300">
                                <template slot-scope="scope">
                                <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)" disabled>Edit</el-button>
                                <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
                                <el-button
                                size="mini"
                                type="success"
                                @click="downFontrunApi(scope.$index, scope.row)" v-if="scope.row.status==  '0'">执行任务</el-button>

                                <el-button
                                size="mini"
                                type="danger"
                                @click="downFontrunApi(scope.$index, scope.row)" v-if="scope.row.status==  '1'">停止任务</el-button>

                                <el-button
                                size="mini"
                                type="danger"
                                @click="downFontrunApi(scope.$index, scope.row)" v-if="scope.row.status==  '2' " >停止本地执行</el-button>

                                <el-button
                                size="mini"
                                type="danger"
                                @click="downFontrunApi(scope.$index, scope.row)" v-if="scope.row.status==  '3' && scope.row.IsDay == false" disabled>再次执行</el-button>

                                <el-button
                                size="mini"
                                type="danger"
                                @click="downFontrunApi(scope.$index, scope.row)" v-if="scope.row.status==  '3' && scope.row.IsDay">再次执行</el-button>

                                <el-button
                                size="mini"
                                type="danger"
                                @click="downFontrunApi(scope.$index, scope.row)" v-if="scope.row.status==  '4' && scope.row.IsDay == false">继续执行</el-button>

                                <el-button
                                size="mini"
                                type="danger"
                                @click="downFontrunApi(scope.$index, scope.row)" v-if="scope.row.status==  '5'">继续执行</el-button>


                                

                                </template>
                                </el-table-column>
                                </el-table>
                            </div>
                            <el-dialog
                                title="选择运行服务地址"
                                :visible.sync="ServiceShow"
                                >
                                    <el-select v-model="ServiceIp" filterable placeholder="请选择" >
                                    <el-option
                                    v-for="item in MasterList"
                                    :key="item.ip"
                                    :label="item.ip"
                                    :value="item.ip">
                                    </el-option>
                                    </el-select>
                                    <div slot="footer" class="dialog-footer">
                                        <el-button type="primary" @click="choseService()">开始执行</el-button>
                                    </div>
                                </el-dialog>
                            
                            <el-dialog
                                title="添加任务"
                                :visible.sync="job_S"
                                width="50%"
                                style="text-align: center;"
                                :before-close="jobhandlerClose">
                                <el-form>
                                <div>
                                <el-form-item label="设备分组">
                                <el-radio v-for="item,index in  grouplist" v-model="groups" :label="item.name">{{item.name}}</el-radio>
                                </el-form-item>
                                </div>

                                <div>
                                <el-form-item label="渠道" >
                                <el-radio-group v-model="apps" @change="Fontbyfroms">

                                <el-radio  label="oppo"  style="margin-top:10%" >oppo</el-radio>
                                <el-radio  label="huawei"  style="margin-top:10%" >华为</el-radio>
                                <el-radio  label="vivo"  style="margin-top:10%">vivo</el-radio>
                                </el-radio-group>
                                </el-form-item>
                                </div>

                                <div >
                                <el-form-item label="字体">
                                <el-select v-model="font" filterable clear  allow-create  placeholder="请选择字体">
                                <el-option v-for="item in fontlist"  :label="item.name" :value="item.name"></el-option>
                                </el-select>
                                </el-form-item>
                                </div>

                                <div >
                                <el-form-item  v-if="IsDown" label="下载次数">
                                <el-input-number v-if="IsDown" v-model="downnum" :step="2"></el-input-number>
                                </el-form-item>
                                </div>

                                <div >
                                <el-form-item v-if="IsPay" label="购买次数">
                                <el-input-number  v-model="paynum" :step="2"></el-input-number>
                                </el-form-item>
                                </div>

                                <div>
                                    <el-form-item label="执行设备">
                                        <div>
                                            <el-transfer v-model="Jobip" :data="ips"
                                            :titles="['在线设备', '任务设备']"
                                            :button-texts="['任务中删除', '增加任务']"
                                            :format="{noChecked: '${total}',hasChecked: '${checked}/${total}'}"
                                            @change="handleChange">
                                            </el-transfer>
                                        </div>
                                    </el-form-item>
                                </div>

                                <div >
                                    <el-form-item label="任务类型">
                                    <el-checkbox v-model="IsDay" label="每天任务"  v-if="IsTime || IsOneTime"  disabled></el-checkbox>
                                    <el-checkbox v-model="IsDay" label="每天任务" v-else="!IsTime" :IsTime="false" @change=""></el-checkbox>
                                    <el-checkbox v-model="IsDay" label="每天任务" v-else="!IsOneTime" :IsOneTime="false" @change=""></el-checkbox>

                                    <el-checkbox v-model="IsTime" label="周期任务" v-if="IsDay || IsOneTime"  disabled></el-checkbox>
                                    <el-checkbox v-model="IsTime" label="周期任务" v-else="!IsDay" :IsDay="false"></el-checkbox>
                                    <el-checkbox v-model="IsTime" label="周期任务" v-else="!IsOneTime" :IsOneTime="false"></el-checkbox>

                                    <el-checkbox v-model="IsOneTime" label="一次性任务" v-if="IsDay || IsTime"  disabled></el-checkbox>
                                    <el-checkbox v-model="IsOneTime" label="一次性任务" v-else="!IsDay" :IsDay="false"></el-checkbox>
                                    <el-checkbox v-model="IsOneTime" label="一次性任务" v-else="!IsTime" :IsTime="false"></el-checkbox>

                                    <el-checkbox v-model="IsDown" label="下载" v-if="IsPay" disabled></el-checkbox>
                                    <el-checkbox v-model="IsDown" label="下载" v-else="!IsPay" :IsPay="false"></el-checkbox>
                                    <el-checkbox v-model="IsPay" label="购买" v-if="IsDown" disabled></el-checkbox>
                                    <el-checkbox v-model="IsPay" label="购买" v-else="!IsDown" :IsDown="false"></el-checkbox>  
                                    </el-form-item> 
                                </div>


                                <div v-if="IsTime">
                                    <el-form-item label="执行时间周期">
                                        <el-date-picker
                                        v-model="RunDate"
                                        type="daterange"
                                        align="right"
                                        unlink-panels
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        :picker-options="pickerOptions">
                                        </el-date-picker>
                                    </el-form-item>
                                </div>
                                </el-form>
                                <el-button @click="Addjob">提交</el-button>
                            </el-dialog>
                        </el-tab-pane>
                        <el-tab-pane label="日志" name="3">
                            <!-- <ul>
                            <div class="coldiv">
                            <li>
                              <div style="text-align: center;">
                              <span id = "ms"></span>
                              </div>
                            </li>
                            </div>
                            </ul> -->
                            <LogView></LogView>

                        </el-tab-pane>
                        <el-tab-pane label="设备实时画面" name="4">
                            <ImgView></ImgView>
                        </el-tab-pane>
                </el-tabs>
            </div>
        </el-main>

    </el-container>
</template>

              
<script>
import axios from 'axios';
import { device,act_run,orders,devupdate,atx,adb,DevGroup,GetDevGroup,Fontbyfrom,addjob,GetJob,downFontrun,updateJob,jobInfo,masters,deljob,computerInfo } from '../../api/autopay';
import LogView from './LogView'
import ImgView from './ShowImg'
export default {
    name: 'autopay',
    data() {
        return {
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                    text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                    text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                }]
            },
            activeIndex: '2',
            search:"",
            dev: [],
            cpt:"查看系统信息",
            ips:[],
            DownFonts : {},
            checkAll: false,
            groups: "",
            downnum:0,
            isIndeterminate: true,
            checkedCities: [],
            checkList: [],
            MasterList: [],
            ServiceShow:false,
            ServiceIp: "",
            show: false,
            dialogVisible: false,
            loadshow: true,
            job_S:false,
            url: "",
            onlineDev: 0,
            fontlist: [],
            joblist:[],
            font:"",
            grouplist :[],
            Jobip:[],
            IsTime:false,
            IsOneTime:false,
            IsDay :true,
            IsDown :true,
            IsPay : false,
            JOB:"",
            msg: "",
            ip: "",
            res: "",
            isCheck : false,
            logip:"192.168.248.179",
            apps: 'oppo',
            centerDialogVisible: false,
            loading: false,
            paynum:0,
            RunDate:["00:00:00", "23:59:59"],
            lastTime: null, //最后一次点击的时间
            currentTime: null, //当前点击的时间
            timeOut: 10 * 60 * 1, //设置超时时间： 10分钟
            multipleSelection: [],
            bgColor: '#778899',
            position: 'top-right',
            logMes:"",

            fabActions: [
              {
                  name: 'cache',
                  icon: 'cached'
              },
              {
                  name: 'alertMe',
                  icon: 'add_alert'
              }
            ]


        }
    },
    components: {
        LogView,ImgView
    },//components
    mounted:function () {
        
        // if (this.timer){
        //     clearInterval(this.timer);
        // }else{
        //    this.timer = setInterval(()=>{
        //     this.DeviceUp();
        //    },100000); 
        // }
        this.GetDevice();
        // this.GetDevGroup()
        // this.Fontbyfrom()
        this.getmyip();
        this.GetJobs();
        this.CheckRes();
        this.GetMaster();
        // this.ShowLog()
    },
    created(){
           //页面刚进入时开启长连接
            // this.Test()
            this.lastTime = new Date().getTime(); 

    },
    destroyed: function() {
    　　　　//页面销毁时关闭长连接
        // this.socket.onclose =  this.close
        // 　　　　this.websocketclose();
    },
    methods: {
        Test(){
            this.socket = new WebSocket('ws://' + window.location.host + '/v1/websockit/get')
            // 监听socket连接
            this.socket.onopen = this.open
            // 监听socket错误信息
            this.socket.onerror = this.error
            // 监听socket消息
            this.socket.onmessage = this.getMessage

            this.socket.onclose = this.websocketclose;
        },
        open: function () {
            console.log("socket连接成功")
        },
        error: function () {
            console.log("连接错误")
        },
        getMessage: function (msg) {
            document.getElementById('ms').innerText =msg.data
        },
        send: function () {
            this.socket.send("ceshi")
        },
        close: function () {
            console.log("socket已经关闭")
        },
        cache(){
          console.log('Cache Cleared');
        },
        alert(){
          alert('Clicked on alert icon');
        },
        handleDelete(index, row) {
            let par = {"jobid":row.jobid}
            deljob(par).then(  res=> {
                let {code,msg,data} = res
                if (code == 200){
                    this.$message("任务已删除");
                    this.GetJobs();
                }else{
                    this.$notify.error({
                      title: '错误',
                      message: '任务删除失败'
                    });
                }
            }).catch(
                function (error){
                    console.log(error);
            })
        },
        GetComputerInfo(datas){
            var that = this;
            this.joblist = []
            for (var i = datas.length - 1; i >= 0; i--) {
                var item = datas[i]
                let par = {"ip":datas[i].master}
                item["SysInfo"]= "未获取到系统信息"
                computerInfo(par).then(res=> {
                    let {code,msg,data} = res
                    if (code == 200){
                        item["SysInfo"]= data
                    }
                }).catch(
                     function (error){
                        console.log(error);
                })
                that.joblist.push(item)
            }
            
        },
        CheckRes(){
            if (this.isCheck){
               setInterval(this.CheckJobStatus, 1000); 

            }else{
                setInterval(this.Cronrefresh, 80000); 
            }
            
            
        },
        Cronrefresh(){
            // 定期刷新任务
            if (!document.hidden){
                this.GetJobs();
            }else{
                console.log("页面被隐藏了");
            }
            
        },
        CheckJobStatus(){
            tmp = jobInfoApi(this.JOB)
            if ( tmp == "3") {
                this.$message("任务"+this.JOB+"已完成");
                this.isCheck = false;
                this.GetJobs();
            }else{
                this.GetJobs()
            }
        },
        GetMaster(){
            var that = this;
            masters().then(res => {
                let {code,msg,data} = res;
                if (code == 200){
                    that.MasterList = data;
                }else{
                }
            }).catch(
                function(error) {
                    that.$message.error("获取Master接口请求失败:\n"+error);
            })   
        },
        jobInfoApi (jobid) {
            let par = {
                "jobid": jobid
            }
            jobInfo(par).then( res => {
                let {code,msg,data} = res;
                if (code == 200){
                    return data.status;
                }else{

                }
            }).catch(
                function(error) {
                    this.$message.error("获取任务详情接口请求失败:\n"+error);
                }

            )
            return ""
        },
        jobdialogshow(){
            var that = this;
            that.job_S = true;
            that.GetDevice();
            that.GetDevGroup();
            that.Fontbyfroms();
        },
        updateJobApi(row){
            let par = {"jobid": row.jobid,"Status": "4"}
            updateJob(par).then(res =>{
                let {code,msg,data} = res;
                if (code == 200) {
                    this.$message("任务已停止成功")
                    this.GetJobs();
                }else{
                    this.$message.error("任务停止操作失败"+data);
                }
            }).catch(
            function(error) {
            // body...
            this.$message.error("接口请求失败:\n"+error);
            })
        },
        handleChange(value, direction, movedKeys) {
            console.log(value, direction, movedKeys);
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleSelect(key, keyPath) {
            console.log(key, keyPath);
        },
        choseService(index, row){
            this.DownFonts["ServiceIp"] = this.ServiceIp;
            this.isCheck = true;
            downFontrun(this.DownFonts).then(res =>{
              let {code,msg,data} = res;
              if (code == 200) {
                this.$message("开始执行任务 ")
                this.GetJobs();
                this.ServiceShow = false;
                this.DownFonts = {};
              }else{
                this.$message.error(data);
              }
            }).catch(
                function(error) {
                  this.$message.error("执行任务接口请求失败:\n");
                }
            )
            

            this.ServiceIp = "";
        },
        downFontrunApi(index, row){
            
            if (row.status == "1"){
                // 点击后如果任务执行中，则停止任务
                row.status = "4"
                this.updateJobApi(row)
                return
            }else if (row.status == "2"){
                row.status = "4"
                this.updateJobApi(row)
                return
            }else if (row.status == "4"){
                
            }
            
            this.GetMaster();
            this.ServiceShow = true;
            var fonts = [];
            var IpList = [];
            fonts.push(row.font);
            IpList.push(row.ip);
            this.JOB = row.jobid;
            let par = {"Count": row.runnum,"Distribution": false,"Fonts": fonts,"Ips": IpList,"IsDay": true,"JobName": row.jobid,"Platform": row.platform,"Status": "-1","Type": row.types, "IsPay": row.IsPay,"IsDown": row.IsDown}
            this.DownFonts =  par;
      },

      GetJobs() {
        GetJob().then(res =>{
            let {code,msg,data} = res;

            if (code == 200){
                this.joblist  = data
                this.GetComputerInfo(data);
            }
        })
      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      querySearchAsync(queryString, cb) {
        return 123;
        // var restaurants = this.restaurants;
        // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

        // clearTimeout(this.timeout);
        // this.timeout = setTimeout(() => {
        //   cb(results);
        // }, 3000 * Math.random());
      },
      Addjob(){

        var that = this;
        var Jobtype = "0"
        if (that.IsDay ){
            Jobtype = "1" //每天任务
        }else if (that.IsTime ) {
            Jobtype = "2" //周期任务
        }else if(that.IsOneTime) {
            Jobtype = "3" //一次性任务
        }
        let par = {
            
          "downcount": that.downnum,
          "count": that.paynum,
          "name": that.font,
          "platform": that.apps,
          "groups": that.groups,
          "ip":that.Jobip,
          "ispay": that.IsPay,
          "isdown":that.IsDown,
          "isday": that.IsDay ,
          "istime": that.IsTime ,
          "rundate": that.RunDate ,
          "types": Jobtype
        }
        addjob(par).then(res =>{
          let {code,msg,data} = res;
          if (code == 200) {
            that.$message("任务添加成功")
            that.job_S = false;
            that.GetJobs();
          }else{
            that.job_S = true;
            that.$message.error(data);
          }
        })
      },
      tipmsg(item){
        if (item.groups == ""){
          return "未分组"
        }else{
          return "分组为"+item.groups
        }

      },
      jobhandlerClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});

      },
      GetDevGroup() {

        GetDevGroup().then( res =>{

          let { code, msg, data } = res;
          console.log(code, msg, data);
          if (code == 200){
            this.grouplist = data;
          }
        } )
      },
      Fontbyfroms() {
        console.log(this.apps);
        var par = {"platfrom":this.apps}
        Fontbyfrom(par).then( res => {
          let { code,msg,data } = res;
          console.log(code,msg,data);
          if (code == 200){
            this.fontlist = data;
            this.font = "";
          }
        }
          )
      
      },
      checkgroup(item){

        if (item.groups == ""){
          return false
        }else{
          return true
        }
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },

      initWebSocket(){ //初始化weosocket

          this.websock =  new WebSocket('ws://' + window.location.host + '/v1/websockit/get');//这个地址由后端童鞋提供
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;
    },
        websocketonopen(){ //连接建立之后执行send方法发送数据
          this.websocketsend("hi test message")
          // console.log(111);
        },
        websocketonerror(){//连接建立失败重连
          this.initWebSocket()
        },
        websocketonmessage(evt){
          let _this = this //数据接收
          console.log(evt);
           
          var tmp = evt.data.replace(/\\/g,"%");
          var tmp1 = tmp.replace("[{","");
          var tmp2 = tmp1.replace("}]","");
          var str = tmp2.replace("%n","");
          document.getElementById('ms').innerText = unescape(str)+"\n";
          

          // if ( evt.data.indexOf("\\u") != -1) {
          //     document.getElementById('ms').innerText= this.Hanzi(evt.data);
          // }else{
          //     // console.log(evt.data);
          //     document.getElementById('ms').innerText= evt.data;
          // }
          
        },
        websocketsend(Data){//数据发送
          this.websock.send(Data)
        },
        websocketclose(e){  //关闭
          // console.log('断开连接', e)
        },
        upGroup(){
          var that = this;
          that.dialogVisible = false;
          
          let par = {"iplist":that.checkedCities,"group":that.msg};
          console.log(par);
          DevGroup(par).then( res =>{
            let { code, msg, data } = res;
              if (code == 200){
                this.$message(
                  {
                    message: "更新成功",
                    type: 'success'
                  }
                )
                that.msg = "";
                that.checkedCities = [];
              }else{
                this.$message.error("数据更新失败");
              }

            }).catch(() => {
                this.$message.error("数据请求失败");
          });
        },
        ShowIp(){
          
          var that = this;
          that.dialogVisible = true;
          
        },
        GetDevice() {
            var that = this;
            device().then(res => {
                let { code, msg, data } = res;

                if (code == 200){
                    if (data != undefined && data.length == 0) {
                        this.$message("无在线设备，请确认设备已连接");
                    }
                    else{
                        this.dev = data;
                        this.onlineDev = data.length;
                        this.ips = [];
                        for (let i = 1; i< this.onlineDev; i++) {
                            this.ips.push({
                            key: data[i].ip,
                            label: `${ data[i].ip }`,
                            disabled: data[i].isbusy
                            });
                        }
                    }
                    
                }

            }).catch( 
                function(error) {
                    that.$message.error("获取在线设备接口请求失败:"+error+"\n");
                }
                
            );
        },
        getmyip(){
          var os = require('os'), ipaddress = '', ifaces = os.networkInterfaces() // 获取本机ip
          this.$message(ifaces);
          out:
          for (var i in ifaces) {
            for (var j in ifaces[i]) {
              var val = ifaces[i][j]

              if (val.family === 'IPv4' && val.address !== '127.0.0.1') {
                ipaddress = val.address
                break out
              }
            }
          }
          // module.exports = ipaddress
          
          
        },
        actRun() {
            
            this.res = "";
    

            if (this.dev!=undefined && this.dev.lenth != 0) {
              
              for (var i =  0; i < this.dev.length; i++) {
                if (this.dev[i].Online == true) {
                  if (this.apps == "huawei" &&  (this.dev[i].name == this.apps || this.dev[i].name == "HONOR")){
                    this.url = "http://"+this.dev[i].ip+":7912/remote";
                    this.ip = this.dev[i].ip;
                  }else if (this.dev[i].name.toLowerCase() == this.apps){
                    this.url = "http://"+this.dev[i].ip+":7912/remote";
                    this.ip = this.dev[i].ip;
                  }
                  
                  
                }
              }
              if(this.ip != ""){
                this.show = true;
                this.centerDialogVisible = true;
                let par = {"app":this.apps,"ip":this.ip };
                act_run(par).then(res => {
                let { code, msg, data } = res;
                this.res = data;
                console.log(data);
                if (code != 200) {
                  this.$message.error(data);
                  this.show = false;
                  this.centerDialogVisible = false;
                }

                }
                ).catch( () => {
                    this.$message.error("数据请求失败");
                });;
              }else{

                this.$message.error(this.apps+"无在线设备");
              }
              
            }
            else{
              this.$message.error("无在线设备，请确认设备已连接，点击更新设备按钮重新获取设备列表");
            }
        },

        Hanzi(msg) {
          msg = msg.split("\\u");
          var str ='';
        
          for(var i=0;i<msg.length;i++){
            console.log(msg[i]+"\n");
            str+=String.fromCharCode(parseInt(msg[i],16).toString(10));
              
          } 

          return str+"\n";
        },
        Atx(){
          this.loading = true;
          atx().then(res => {
            let { code, msg, data } = res;
            if (code == 200) {
              this.$message(data);
              this.GetDevice();
            }else{
              this.$message.error(data);
            }
          }).catch( () => {
                    this.$message.error("数据请求失败");
                });;
          
          
          this.loading = false;
        },
        handleEdit(index, row) {
          console.log(index, row);
        },
        handleCheckAllChange(val) {
         
          for (var i = this.dev.length - 1; i >= 0; i--) {
            this.checkList.push(this.dev[i].ip)
          }
          this.checkedCities = val ? this.checkList : [];
          this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
          let checkedCount = value.length;
          this.checkAll = checkedCount === this.dev.length;
          this.isIndeterminate = checkedCount > 0 && checkedCount < this.dev.length;
        },
        DeviceUp(){
          this.loading = true;
          devupdate().then(res => {
            let { code, msg, data } = res;
            if (code == 200) {
              this.$message("设备信息已更新");
            }else{
              this.$message.error(data);
            }
          }).catch( () => {
                    this.$message.error("数据请求失败");
                });;
          
          this.GetDevice();
          this.loading = false;
        },
    }//
}

</script>

<style>
  /*html, body {
    margin: 0;
    background-color: hsla(0,0%,100%,.9);
    width: 100%;
    height: 100%;
  }*/
  .gbtn{
    text-align: center;
  }
  .el-header, .el-footer {
    background-color: rgba(87, 163, 243, 0.09);
    color: #333;
    text-align: center;
    line-height: 60px;
  }
  
  .el-aside {
    background-color: #D3DCE6;
    color: #333;
    text-align: center;
    line-height: 400px;
  }
/*  
 .el-main {
    background-color: rgba(233, 238, 243, 0.23);
    color: #333;
    text-align: center;
    line-height: 160px;
  }*/
  
/*  body > .el-container {
    margin-bottom: 40px;
    background: url(../img/banner2.jpg)no-repeat center;
    background-size: cover;
  }
*/
  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }
  
  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }
  .time {
    font-size: 13px;
    color: #999;
  }
  
  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }
/*  #cols {
    background-color: rgba(233, 238, 243, 0.23);
  }*/
  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
      display: table;
      content: "";
  }
  
  .clearfix:after {
      clear: both
  }
  .colip{
    height: 480px;
  }
  .coldiv{
    min-height: 100px;
  }
  #ptitle{
    margin-left: 50%;
  }
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
    .transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
  }
  
</style>
